package com.zjw.remotecall;


import android.content.Context;

import androidx.annotation.NonNull;

import com.zjw.remotecall.call.IRemoteCall;
import com.zjw.remotecall.call.WithIt;
import com.zjw.remotecall.streamacceptor.RemoteCallResult;
import com.zjw.remotecall.utils.RemoteUtils;


/**
 * 跨进程回调管理类
 */
public final class RemoteCallManager {

    private static final String TAG = "RemoteManager";

    private static int MAX_BYTES_LIMIT = 1024 * 500;

    private static int TIMEOUT = 10_000;

    private static final String DESCRIPTOR_PREV = "com.zjw.remotecall.";

    private final String mDescriptor;

    private static volatile RemoteCallManager INSTANCE;

    @NonNull
    public static RemoteCallManager defaultImpl() {
        if (INSTANCE == null) {
            synchronized (RemoteCallManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RemoteCallManager(RemoteUtils.createDefaultDescriptor());
                }
            }
        }
        return INSTANCE;
    }

    public RemoteCallManager(String descriptor) {
        this.mDescriptor = descriptor;
    }

    public RemoteCallManager(@NonNull Context context) {
        this.mDescriptor = DESCRIPTOR_PREV + context.getPackageName();
    }

    public <T> IRemoteCall remoteCall(WithIt<T> callback) {
        return new IRemoteCall(mDescriptor) {
            @Override
            public void onResult(RemoteCallResult obj) {
                callback.onWith(obj.getResult());
            }
        };
    }

    public IRemoteCall remoteCallResult(WithIt<RemoteCallResult> callback) {
        return new IRemoteCall(mDescriptor) {
            @Override
            public void onResult(RemoteCallResult obj) {
                callback.onWith(obj);
            }
        };
    }

    /**
     * 分流byte最大大小
     */
    public static void controlMaxBytesLimit(int bytesCount) {
        MAX_BYTES_LIMIT = bytesCount;
    }

    /**
     * 分流byte存活时长
     */
    public static void controlBytesTimeOut(int timeout) {
        TIMEOUT = timeout;
    }

    /**
     * 分流byte最大大小
     */
    public static int getMaxBytesLimit() {
        return MAX_BYTES_LIMIT;
    }

    public static long getBytesTimeOut() {
        return TIMEOUT;
    }
}
